import axios from 'axios'
import router from '@/router'

// 请求封装
export const request = axios.create({
  baseURL: 'https://xiaozude.cn:8888',
  headers: {
    'Content-Type': 'application/json'
  }
})



// 请求拦截器
request.interceptors.request.use(
  function (config) {
    const token = localStorage.getItem('auth_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  }, function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器 结果 服务器返回的在data里 res.data 
request.interceptors.response.use(
	function (response) {
		// console.log(response)
		if (response.status === 200) {
			if(response.data.data) {
				const { token } = response.data.data
				if (token) {
					localStorage.setItem('auth_token', token)
				}
			}
		}
		return response   // 可以返回res.data
	}, function (error) {		
		const { status } = error.response
		if(status === 400) {
			console.log(400);
		} else if (status === 401) {
			localStorage.removeItem('auth_token')			
			router.push({name: "login"});
		} else if (status === 403) {
			console.log(403);
		} else if (status === 404) {
			console.log(404);
		} else if (status >= 500) {
			console.log(500);
		}
		return Promise.reject(error)
	}
)
